import logging
from logging.handlers import RotatingFileHandler
from PyQt5.QtWidgets import QPlainTextEdit
import sys

class QTextEditLogger(logging.Handler):
    def __init__(self, text_edit):
        super().__init__()
        self.text_edit = text_edit
        self.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
        
    def emit(self, record):
        msg = self.format(record)
        self.text_edit.appendPlainText(msg)

def setup_logging(text_edit=None):
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)  # 设置全局日志级别为DEBUG
    
    # 1. 文件日志处理器
    file_handler = RotatingFileHandler(
        'cat_face_detection.log', 
        maxBytes=5 * 1024 * 1024, 
        backupCount=3,
        encoding='utf-8'
    )
    file_handler.setLevel(logging.DEBUG)  # 文件处理器记录DEBUG及以上级别
    
    # 2. 控制台日志处理器
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(logging.DEBUG)  # 控制台输出DEBUG及以上级别
    
    # 3. UI日志处理器
    ui_handler = None
    if text_edit:
        ui_handler = QTextEditLogger(text_edit)
        ui_handler.setLevel(logging.INFO)  # 注意这里使用logging.INFO（全大写）
    
    # 统一日志格式
    formatter = logging.Formatter('%(levelname)s - %(message)s')
    file_handler.setFormatter(formatter)
    console_handler.setFormatter(formatter)
    if ui_handler:
        ui_handler.setFormatter(formatter)  # 使用统一的格式
    
    # 添加处理器
    logger.addHandler(file_handler)
    logger.addHandler(console_handler)
    if ui_handler:
        logger.addHandler(ui_handler)
    
    return logger